<?php
class TaskCommentController  extends Zone_Action{	
	protected function fields( $default=NULL ){
		$data = array(
			content => array(
				type 		=> 'HTML',
				no_empty 	=> true,
				min_length	=> 3,
				form_label 	=> 'Nội dung'
			),
			task_id => array(
				type 	   => 'INT',
				form_label => 'Công việc'
			),			
			date_updated	=>array(
				type	=> 'NONE',
				default_value => new Model_Expr("NOW()")
			)	
		);
		/* Neu chinh sua thi cac thong so duoc mac dinh trc*/
		if( is_array( $default ) ){
			foreach( $data as $k => $config ){
				if( $config['type'] != 'NONE' && isset( $default[$k] ) ){
					$data[$k]['default_value'] = $default[$k];
				}
			}
		}	
		return $data;	
	}

	protected function fieldFile(){
		$data = array(
			files => array(
				type 	=> 'FILES',
				path	=> 'files/task/'
			)
		);
		return $data;	
	}
	
	public function initAction(){
		if(!$this->hasRole('task')){
			$this->setContent(error('Bạn không được phép truy cập phân hệ này'));	
			$this->stop();
		}		
	}	
			
	public function indexAction(){}
	
	/* Upload like ajax */
	public function uploadAction(){
		$this->removeLayout();
		$user_id = get_user_id();		
		$comment_id = get("ID",0);
			
		$comment = $this->Model->fetchRow("SELECT * FROM `tasks_comments` 
			WHERE `ID`='$comment_id' AND `created_by_id`='$user_id'");		
		
		if(!$comment){
			return $this->setJSON(array(
				alert	=> 'Phản hồi đã bị xóa hoặc không tồn tại.'
			));
		}
		
		$task_id = $comment['task_id'];
		
		if( $task_id ){
			$post = $this->Model->fetchRow("SELECT * FROM `tasks` WHERE `ID`='$task_id'");				
				
			if( !$post){
				return $this->setJSON(array(
					alert	=> 'Công việc đã bị xóa hoặc không tồn tại'
				));
			}
			
			if( $post['created_by_id'] != get_user_id() ){
				if( !$this->Model->fetchRow("SELECT * FROM `tasks_users` WHERE `user_id`='$user_id' AND `task_id`='$task_id'") ){
					return $this->setJSON(array(
						alert	=> error("Bạn không có quyền tải file lên.")
					));
				}			
			}	
		}
		
		if( isPost() ){
			loadClass("ZData");
			$f = new ZData();

			$f->addField(array(
				file => array(
					type 		=> 'FILE',
					path		=> 'files/task/',
					no_empty	=> true
				)
			));
			
			$data = $f->getData();		
			
			if( is_array( $data ) ){
				$file = $data['file'];
				$this->Model->insert('tasks_comments_files',array(
					comment_id		=> $comment_id,
					name			=> $file[0],
					type			=> $file[1],
					size			=> $file[2],
					filename		=> $file[3]
				));
				
				$file_id = $this->Model->lastId();				
				return $this->setJSON(array(
					content	=> "<div class='x-file-info'><input checked type='checkbox' name='files[]' value='$file_id'/>
								<a href='".ctrUrl($this)."/File?ID=$file_id' target='_blank'>{$file[3]} {$file[2]} KB	</a>
								</div>"
				));
			}else{
				return $this->setJSON(array(
					alert => $data
				));				
			}			
		}
		$this->setJSON(array(
			alert	=> 'Truy cập không được cho phép.'
		));
	}	
	
	public function addAction(){
		$this->removeLayout();
		$user_id = get_user_id();		
		$task_id = getInt('task_id',0);	
		$this->set('task_id', $task_id);		
				
		$post = $this->Model->fetchRow("SELECT * FROM `tasks` 
			WHERE `ID`='$task_id' AND `is_draft`='no' LIMIT 1");		

		if( !$post ){
			return $this->setJSON(array(
				alert => 'Công việc đã bị xóa hoặc không tồn tại.'
			));
		}
		
		if( $post['created_by_id'] != $user_id ){
			if( !$this->Model->fetchRow("SELECT * FROM `tasks_users` 
				WHERE `task_id`='$task_id' AND `user_id`='$user_id'") ){
				return $this->setJSON(array(
					alert => 'Bạn không có quyền đăng thảo luận trong công việc này.'
				));			
			}
		}
				
		$comment = $this->Model->fetchRow("SELECT * FROM `tasks_comments` 
			WHERE `created_by_id`='$user_id' AND `is_draft`='yes' LIMIT 1");
		
		if( isset($_REQUEST['comment_id'])){
			$a = $this->Model->fetchRow("SELECT `a`.*,`b`.`username` as `created_by_name`
				FROM `tasks_comments` as `a` 
				LEFT JOIN `users` as `b` ON `a`.`created_by_id`=`b`.`ID`
				WHERE `a`.`ID`='".get('comment_id')."'");
			if($a){
				$this->set('quote',"<div class='quote'><i>Trích dẫn từ <b>{$a['created_by_name']}</b>:</i><br/>{$a['content']}</div>");
			}	
		}
		
		if( $comment ){
			$comment_id = $comment['ID'];
			$files = $this->Model->fetchAll("SELECT * 
				FROM `tasks_comments_files` WHERE `comment_id`='$comment_id'");	
		}else{
			$comment = array(
				is_draft		=> 'yes',
				created_by_id	=> $user_id
			);						
			$this->Model->insert('tasks_comments', $comment);
			$comment_id = $this->Model->lastId();
			$comment['ID'] = $comment_id;	
			$files = array();	
		}
		
		$this->set(array(			
			post	=> $comment,
			files 	=> $files	
		)); 
		
		if(isPost()){
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->fields());
			$data = $form->getData();
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message	=> error($data)
				));
			}				

			$data['is_draft'] = 'no';		
			$data['date_created'] = new Model_Expr("NOW()");		
			$data['created_by_id'] = get_user_id();		
			
			$this->Model->update('tasks_comments',$data,"`ID`='$comment_id'");
			
			/* bum for task */
			$this->Model->update('tasks',array(
				date_active	=> new Model_Expr('NOW()')
			),"`ID`='$task_id'");
			
			
			/* Xoa tat ca nhung file dinh kem khong checked*/
			$files_selected = (array)$_POST['files'];
			$files = $this->Model->fetchAll("SELECT * FROM `tasks_comments_files` WHERE `comment_id`='$comment_id'");
			
			foreach( $files as $f ){
				if( !in_array( $f['ID'], $files_selected ) ){
					$this->Model->delete('tasks_comments_files',"`ID`='{$f['ID']}'");
					@unlink("files/task/{$f['name']}");
				}
			}	
			
			$users = $this
				->Model->fetchAll("SELECT `a`.`ID` 
					FROM `users` as `a`
					LEFT JOIN `tasks_users` as `b`
					ON `a`.`ID`=`b`.`user_id` AND `b`.`task_id`='$task_id'
					WHERE `b`.`task_id`='$task_id' AND `a`.`is_deleted`='no'");
					
			foreach( $users as $u ){	
				$this->Model->insert('notices',array(
					created_by_id	=> $user_id,
					user_id			=> $u['ID'],
					title			=> $post['title'],
					url				=> "#Task/Index/View?ID=$task_id",
					date			=> new Model_Expr("NOW()"),
					content			=> "Thảo luận mới"
				));					
			}				

			return $this->setJSON(array(
				redirect => "#Task/Index/View?ID=$task_id"
			));				
		}		
	}
	
	public function editAction(){
		$user_id = get_user_id();		
		$comment_id = get('ID',0);
		$this->removeLayout();
		$comment = $this->Model->fetchRow("SELECT * FROM `tasks_comments`
			WHERE `is_draft`='no' AND `ID`='$comment_id' LIMIT 1");
		
		if( $comment && $comment['created_by_id'] != $user_id ){
			return $this->setJSON(array(
				alert	=> 'Bạn không có quyền sửa thảo luận này.'
			));
		}
		
		if( !$comment){
			return $this->setJSON(array(
				alert	=> 'Phản hồi đã bị xóa hoặc không tồn tại.'
			));
		}

		$task_id = $comment['task_id'];
		$post = $this->Model->fetchRow("SELECT * FROM `tasks` WHERE `ID`='$task_id'");				
			
		if( $post && $post['created_by_id'] != $user_id ){
			if( !$this->Model->fetchRow("SELECT * FROM `tasks_users` WHERE `task_id`='$task_id' AND `user_id`='$user_id'") ){
				return $this->setJSON(array(
					alert => 'Bạn không có quyền xem công việc này'
				));			
			}
		}
		
		if( !$post ){
			return $this->setJSON(array(
				alert => 'Công việc đã bị xóa hoặc không tồn tại'
			));
		}
		
		$this->set('post',$comment);
		$files = $this->Model->fetchAll("SELECT * FROM `tasks_comments_files` WHERE `comment_id`='$comment_id'");	
		$this->set('files',$files);
		
		if(isPost()){
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->fields($comment));
			$data = $form->getData();
		
			if( is_array( $data )){
				$data['is_draft'] = 'no';		
				$this->Model->update('tasks_comments',$data,"`ID`='$comment_id'");
				$this->Model->update('tasks',array(
					date_active	=> new Model_Expr('NOW()')
				),"`ID`='$task_id'");
			
				$users = $this
					->Model->fetchAll("SELECT `a`.`ID` 
						FROM `users` as `a`
						LEFT JOIN `tasks_users` as `b`
						ON `a`.`ID`=`b`.`user_id` AND `b`.`task_id`='$task_id'
						WHERE `b`.`task_id`='$task_id' AND `a`.`is_deleted`='no'");
				
				foreach( $users as $u ){	
					$this->Model->insert('notices',array(
						created_by_id	=> $user_id,
						user_id			=> $u['ID'],
						title			=> $post['title'],
						url				=> "#Task/Index/View?ID=$task_id",
						content			=> "Thảo luận mới chỉnh sửa",
						date			=> mysql_date()
					));					
				}			
			
				/* Xoa tat ca nhung file dinh kem khong checked*/
				$files_selected = (array)$_POST['files'];
				$files = $this->Model->fetchAll("SELECT * FROM `tasks_comments_files` 
					WHERE `comment_id`='$comment_id'");
				
				foreach( $files as $f ){
					if( !in_array( $f['ID'], $files_selected ) ){
						$this->Model->delete('tasks_comments_files',"`ID`='{$f['ID']}'");
						@unlink("files/task/{$f['name']}");
					}
				}	
				return $this->setJSON(array(
					redirect => "#Task/Index/View?ID=$task_id"
				));				
			}else{
				return $this->setJSON(array(
					message	=> error($data)
				));
			}			
		}		
	}	

	public function deleteAction(){
		$user_id	= get_user_id();	
		$comment_id = get('ID',0);	
		$comment = $this->Model->fetchRow("SELECT * FROM `tasks_comments` 
			WHERE `ID`='$comment_id' AND `is_draft`='no'");
		if( !$comment ){
			return $this->setJSON(array(
				alert => 'Thảo luận không tồn tại'
			));
		}		
		
		if( $comment['created_by_id'] != $user_id ){
			return $this->setJSON(array(
				alert => 'Bạn không có quyền này.'
			));	
		}
		
		$files = $this->Model->fetchAll("SELECT * FROM `tasks_comments_files` WHERE `comment_id`='$comment_id'");
		$this->Model->delete('tasks_comments_files',"`comment_id`='$comment_id'");
		$this->Model->delete('tasks_comments',"`ID`='$comment_id'");
		
		foreach( $files as $f ){
			@unlink("files/task/{$f['name']}");
		}	
		$this->setJSON(array(
			redirect => "#Task/Index/View?ID={$comment['task_id']}"
		));	
	}
		
	public function fileAction(){
		$file_id = get('ID',0);
		$user_id = get_user_id();
		
		$file = $this
			->Model->fetchRow("SELECT *	FROM `tasks_comments_files` WHERE `ID`='$file_id' LIMIT 1");
		
		if( !$file ){
			return $this->setError('404');
		}
		
		$comment_id = $file['comment_id'];		
		$comment = $this->Model->fetchRow("SELECT * FROM `tasks_comments` WHERE `ID`='$comment_id' AND `is_draft`='no'");
		if( !$comment ){
			return $this->setError('404');
		}
		
		$task_id = $comment['task_id'];
		$task = $this->Model->fetchRow("SELECT * FROM `tasks` WHERE `ID`='$task_id'");				
			
		if( !$task ){
			return $this->setError('404');
		}

		if( $task['created_by_id'] != $user_id ){	
			if( !$this->Model->fetchRow("SELECT * FROM `tasks_users` WHERE `task_id`='$task_id' AND `user_id`='$user_id'") ){
				return $this->setError('404');	
			}
		}		
		
		$file_path = "files/task/{$file['name']}";
		if( !file_exists( $file_path ) ){
			return $this->setError('404');
		}		
		if( get('type') == 'icon' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->resize(60, 60);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else if( get('type') == 'view' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else{
			@header("Content-Disposition: attachment; filename={$file['name']}");
			@readfile($file_path);
		}	
	}
}	